package com.example.myapplication2;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;

public class InstallAppActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private static final int READ_EXTERNAL_STORAGE_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_install_app);
        findViewById(R.id.installButton).setOnClickListener(this);

        //输出本应用的provider
        Toast.makeText(this,
                getApplicationContext().getApplicationContext().getPackageName() + ".fileProvider",
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.installButton:
                //判断是否有MANAGE_EXTERNAL_STORAGE权限
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                    //Android版本11
                    Toast.makeText(this,"Android版本11",Toast.LENGTH_SHORT).show();
                    checkAndInstall();
                }else {
                    //android11之前,如何判定安装权限
                    if (checkPermissions(this,PERMISSIONS,READ_EXTERNAL_STORAGE_CODE)) {
                        installApk();
                    }else {

                    }
                }
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void checkAndInstall() {
        if(!Environment.isExternalStorageManager()){
            Intent intent = new Intent();
            //应用的详情设置界面
            intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            //具体某个应用管理页面
            intent.setData(Uri.fromParts("package",getPackageName(),null));
            //跳转应用模式
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else {
            installApk();
        }
    }

    private void installApk() {
        //获取文件地址
        String path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/1.apk";
        System.out.println(path);
        Toast.makeText(this,path,Toast.LENGTH_SHORT).show();
        //包管理器,检查应用正常否
        PackageManager packageManager = getPackageManager();
        PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if(packageArchiveInfo==null){
            Toast.makeText(this,"安装包异常",Toast.LENGTH_SHORT).show();
            return;
        }
        Uri parse = Uri.parse(path);
        //兼容Android7.0 把访问文件的Uri改为FileProovider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            String file_provider = getApplicationContext().getApplicationContext().getPackageName() + ".fileProvider";
            Toast.makeText(this,file_provider,Toast.LENGTH_SHORT).show();
            parse= FileProvider.getUriForFile(this,file_provider,new File(path));
        }
        //跳转应用
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //设置任务栈类型
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Intent的接受者允许读取intent对象携带的URI数据
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //设置Uri的数据类型
        intent.setDataAndType(parse,"application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //查询用户判定结果
        switch (requestCode) {
            case READ_EXTERNAL_STORAGE_CODE:
                if (checkGrant(grantResults)) {
                    Log.d("info", "授权成功");
                    installApk();
                } else {
                    Log.d("info", "授权失败");

                }
                break;
        }
    }
    private boolean checkGrant(int[] grantResults) {
        if (grantResults != null) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    //检查多个权限,返回true表示已完全启用权限,返回false表示未完全启用权限
    private boolean checkPermissions(Activity act, String[] permissions, int requestCode) {
        //判定该系统是否拥有动态权限管理,Android6.0之后才有该功能
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int check = PackageManager.PERMISSION_GRANTED;
            for (String permission : permissions) {
                // 检查权限,返回值为-1,即为无相关权限,0即拥有相关权限
                check = ContextCompat.checkSelfPermission(act, permission);
                //判定权限
                if (check != PackageManager.PERMISSION_GRANTED) {
                    //无相关权限,结束检查
                    break;
                }
            }
            if (check != PackageManager.PERMISSION_GRANTED) {
                //检查到未申请该权限,弹窗申请
                ActivityCompat.requestPermissions(act, permissions, requestCode);
                return false;
            }
        }
        Toast.makeText(this,"权限检查完毕,权限正常",Toast.LENGTH_SHORT).show();
        return true;
    }
}